package org.alvin.i18n.ui;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 映射出新的文件，最后根据文件还原到项目
 */
public class I18nRestoreUtils {

    public static void main(String[] args) throws IOException {
//        String path = "D:/i18n/i18ncode.js";
//        toMap(path);
//        String path = "D:/i18n/map.json";
//        toList(path);
//        toMenu();
//        restore();
//        compare();
//        getChinese();

//        marge();
//        trim();

        autoTransfer();
    }

    public static void toMap(String path) throws IOException {
        byte[] buff = Files.readAllBytes(Paths.get(path));
        String text = new String(buff, StandardCharsets.UTF_8);
        int index = text.indexOf("{");
        JSONObject jsonObject = JSONObject.parseObject(text.substring(index));

        Map<String, List<String>> result = Maps.newHashMap();
        for (Object key : jsonObject.keySet()) {
            JSONObject fileNameRes = jsonObject.getJSONObject(key.toString());
            if (fileNameRes == null) {
                continue;
            }
            for (String pyKey : fileNameRes.keySet()) {
                String value = fileNameRes.getString(pyKey);
                if (result.get(value) == null) {
                    result.put(value, Lists.newArrayList());
                }
                result.get(value).add(key.toString().concat(".").concat(pyKey));
            }
        }
        //
        Map<String, List<String>> sortMap = Maps.newLinkedHashMap();
        List<String> keys = result.keySet().stream().sorted().collect(Collectors.toList());
        //
        for (String key : keys) {
            if (key.isEmpty()) {
                continue;
            }
            sortMap.put(key, result.get(key));
        }
        //
        JSONObject outJson = new JSONObject();
        outJson.putAll(sortMap);
        //
        System.out.println(outJson);
        Files.write(Paths.get("D:/i18n/map.json"), outJson.toJSONString().getBytes(StandardCharsets.UTF_8));
    }

    public static void toList(String path) throws IOException {
        byte[] buff = Files.readAllBytes(Paths.get(path));
        JSONObject jsonObject = JSONObject.parseObject(new String(buff, StandardCharsets.UTF_8));
        JSONObject resultJson = new JSONObject();
        for (Object key : jsonObject.keySet()) {
            JSONArray array = jsonObject.getJSONArray(key.toString());
            if (array != null && !array.isEmpty()) {
                String newKey = array.getString(0);
                resultJson.put(newKey, key);
            }
        }
        Files.write(Paths.get("D:/i18n/list.json"), resultJson.toJSONString().getBytes(StandardCharsets.UTF_8));
    }

    public static void restore() throws IOException {
        List<String> lines = Files.readAllLines(Paths.get("D:/", "i18n", "需要翻译的中文.txt"));

        byte[] buff = Files.readAllBytes(Paths.get("D:/i18n/map.json"));
        JSONObject map = JSONObject.parseObject(new String(buff, StandardCharsets.UTF_8));
        JSONObject resultJSON = new JSONObject();
        for (String line : lines) {
            int index = line.indexOf(":");
            if (index == -1) {
                continue;
            }
            try {
                System.out.println(line);
                String key = line.substring(1, index - 1);
                String value = line.substring(index + 2, line.length() - 1);
                if (value.trim().startsWith("\"")) {
                    value = value.substring(1);
                }
                label:
                for (Object cKey : map.keySet()) {
                    JSONArray array = map.getJSONArray(cKey.toString());
                    for (int i = 0; i < array.size(); i++) {
                        if (array.getString(i).equals(key)) {
                            for (int j = 0; j < array.size(); j++) {
                                resultJSON.put(array.getString(i), value);
                            }
                            break label;
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        //toTree
        JSONObject treeJson = new JSONObject();
        for (String key : resultJSON.keySet()) {
            int index = key.indexOf(".");
            if (index != -1) {
                String firstKey = key.substring(0, index);
                String secondKey = key.substring(index + 1);
                if (!treeJson.containsKey(firstKey)) {
                    treeJson.put(firstKey, new JSONObject());
                }
                treeJson.getJSONObject(firstKey).put(secondKey, resultJSON.getString(key));
            }
        }

        String outString = JSON.toJSONString(treeJson, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);

        Files.write(Paths.get("D:/i18n/newI18n.js"), ("export default " + outString).getBytes(StandardCharsets.UTF_8));

    }

    public static void toMenu() throws IOException {
//        byte[] buff = Files.readAllBytes(Paths.get("D:/i18n/map.json"));
//        JSONArray menuMap = JSONArray.parseArray(new String(buff, StandardCharsets.UTF_8));
        String menus = "[{\"path\":\"welcome\",\"name\":\"首页\"},{\"path\":\"custom\",\"name\":\"客户管理\",\"children\":[{\"path\":\"organization\",\"name\":\"运营商管理\"},{\"path\":\"group\",\"name\":\"集团管理\"},{\"path\":\"associatio\",\"name\":\"合伙人\"}]},{\"path\":\"subStation\",\"name\":\"场站管理\",\"children\":[{\"path\":\"station\",\"name\":\"充电站管理\"},{\"path\":\"stationMeter\",\"name\":\"充电站电表信息\"},{\"path\":\"chargingPile\",\"name\":\"充电桩管理\"},{\"path\":\"rates\",\"name\":\"费率管理\"},{\"path\":\"ratetemplate\",\"name\":\"费率模板\"},{\"path\":\"expirealarm\",\"name\":\"桩续期预警\"},{\"path\":\"iotcard\",\"name\":\"流量卡管理\"},{\"path\":\"reneworder\",\"name\":\"续费订单\"},{\"path\":\"bikechargepileLog\",\"name\":\"单车充电桩日志\"},{\"path\":\"allowcharge\",\"name\":\"允许充电用户\"}]},{\"path\":\"devDebug\",\"name\":\"开发调试\",\"children\":[{\"path\":\"chargingStation\",\"name\":\"电桩操作\"},{\"path\":\"commDebug\",\"name\":\"通讯调试\"},{\"path\":\"carCommDebug\",\"name\":\"汽车系统调试\"},{\"path\":\"workRecord\",\"name\":\"工作数据\"}]},{\"path\":\"funds\",\"name\":\"资金管理\",\"children\":[{\"path\":\"platformFunds\",\"name\":\"平台资金管理\"},{\"path\":\"carrierFundsllist\",\"name\":\"运营商资金管理\"},{\"path\":\"orderlist\",\"name\":\"充电订单\"},{\"path\":\"stationMeterList\",\"name\":\"电站电价订单\"},{\"path\":\"rechargeorderlist\",\"name\":\"充值管理\"},{\"path\":\"refundlist\",\"name\":\"退款记录\"},{\"path\":\"cardlist\",\"name\":\"IC卡管理\"},{\"path\":\"rechargegiftlist\",\"name\":\"充值活动\"},{\"path\":\"rechargesetlist\",\"name\":\"充值金额\"},{\"path\":\"announcementList\",\"name\":\"充值活动公告\"},{\"path\":\"mouthly\",\"name\":\"包月活动\"},{\"path\":\"mouthlyitem\",\"name\":\"活动发布\"},{\"path\":\"reneworder\",\"name\":\"续费订单\"}]},{\"path\":\"statistics\",\"name\":\"数据统计\",\"children\":[{\"path\":\"siteStatistics\",\"name\":\"单车站点统计\"},{\"path\":\"carSiteStatistics\",\"name\":\"汽车站点统计\"},{\"path\":\"dashboard\",\"name\":\"仪表盘\"},{\"path\":\"organization\",\"name\":\"运营商统计\"},{\"path\":\"userstatstics\",\"name\":\"用户统计\"},{\"path\":\"platform\",\"name\":\"平台统计\"},{\"path\":\"chargepile\",\"name\":\"充电桩统计\"}]},{\"path\":\"operator\",\"name\":\"平台运营\",\"children\":[{\"path\":\"rechargestatistics\",\"name\":\"充值统计\"},{\"path\":\"userBehavior\",\"name\":\"用户行为\"},{\"path\":\"organizationBehavior\",\"name\":\"运营商统计报表\"},{\"path\":\"bicycleStatistics\",\"name\":\"单车数据统计\"},{\"path\":\"carStatistics\",\"name\":\"汽车数据统计\"}]},{\"path\":\"settings\",\"name\":\"系统设置\",\"children\":[{\"path\":\"job\",\"name\":\"任务管理\"},{\"path\":\"dict\",\"name\":\"数据字典\"},{\"path\":\"versionlog\",\"name\":\"软件版本日志\"},{\"path\":\"requirements\",\"name\":\"开发需求\"},{\"path\":\"enterapplet\",\"name\":\"入驻小程序信息\"},{\"path\":\"withdrawRuleList\",\"name\":\"平台提现规则\"},{\"path\":\"tag\",\"name\":\"标签设置\"},{\"path\":\"membervehicleList\",\"name\":\"车辆管理\"},{\"path\":\"msiteresource\",\"name\":\"移动端菜单\"},{\"path\":\"secret\",\"name\":\"密钥管理\"},{\"path\":\"adplatform\",\"name\":\"广告应用管理\"},{\"path\":\"adspace\",\"name\":\"广告位管理\"},{\"path\":\"blacklist\",\"name\":\"设备黑名单管理\"},{\"path\":\"upgradefile\",\"name\":\"升级文件\"}]},{\"path\":\"miniapp\",\"name\":\"小程序设置\",\"children\":[{\"path\":\"chargeargmt\",\"name\":\"充值协议\"},{\"path\":\"wxappqrsettings\",\"name\":\"二维码设置\"},{\"path\":\"wxmch\",\"name\":\"微信商户号\"},{\"path\":\"wxfeedback\",\"name\":\"反馈和报修\"},{\"path\":\"join\",\"name\":\"加入我们\"},{\"path\":\"recommend\",\"name\":\"推荐建站\"}]},{\"path\":\"wxusermanage\",\"name\":\"微信用户管理\",\"children\":[{\"path\":\"member\",\"name\":\"微信用户管理\"}]},{\"path\":\"usermanage\",\"name\":\"后台用户管理\",\"children\":[{\"path\":\"user\",\"name\":\"后台用户\"},{\"path\":\"menuresource\",\"name\":\"资源管理\"},{\"path\":\"role\",\"name\":\"角色权限管理\"}]},{\"path\":\"withdraw\",\"name\":\"提现管理\",\"children\":[{\"path\":\"applywithdraw\",\"name\":\"申请提现\"},{\"path\":\"withdrawalsrecord\",\"name\":\"提现记录\"},{\"path\":\"associateWxList\",\"name\":\"微信账号\"}]},{\"path\":\"datav\",\"name\":\"运营统计\",\"children\":[]},{\"path\":\"car\",\"name\":\"充电汽车管理\",\"children\":[{\"path\":\"carstation\",\"name\":\"汽车充电站点\"},{\"path\":\"carchargepile\",\"name\":\"汽车充电桩\"},{\"path\":\"carratetemplate\",\"name\":\"汽车桩费率管理\"},{\"path\":\"carorder\",\"name\":\"汽车桩订单\"},{\"path\":\"deposit\",\"name\":\"占位费管理\"},{\"path\":\"depositorder\",\"name\":\"占位费订单\"},{\"path\":\"seqammeter\",\"name\":\"有序充电电表\"},{\"path\":\"stationArea\",\"name\":\"站点停车区域\"},{\"path\":\"stationParkingNo\",\"name\":\"站点停车位\"},{\"path\":\"carchargepileLog\",\"name\":\"汽车充电桩日志\"}]},{\"path\":\"pointsmall\",\"name\":\"积分商城\",\"children\":[{\"path\":\"goods\",\"name\":\"商品管理\"},{\"path\":\"couponlist\",\"name\":\"优惠券管理\"},{\"path\":\"grandRecord\",\"name\":\"兑换记录\"},{\"path\":\"couponrule\",\"name\":\"优惠券规则\"},{\"path\":\"membercoupon\",\"name\":\"用户优惠券\"}]},{\"path\":\"simcard\",\"name\":\"流量卡管理\",\"children\":[{\"path\":\"vendor\",\"name\":\"流量卡厂商\"},{\"path\":\"apiconfig\",\"name\":\"流量卡API配置\"},{\"path\":\"cardlist\",\"name\":\"流量卡\"}]},{\"path\":\"hlht\",\"name\":\"互联互通\",\"children\":[{\"path\":\"hlhtcompanyinfo\",\"name\":\"互联互通账号\"},{\"path\":\"hlhtoperatorstation\",\"name\":\"互联互通站点信息\"}]},{\"path\":\"fault\",\"name\":\"故障管理\",\"children\":[{\"path\":\"faultlist\",\"name\":\"故障管理\"},{\"path\":\"mpuserlist\",\"name\":\"故障推送人员\"}]},{\"path\":\"parking\",\"name\":\"停车管理\",\"children\":[{\"path\":\"parking_lock_list\",\"name\":\"车位锁管理\"},{\"path\":\"parking_lock_type\",\"name\":\"车位锁类型\"}]}]";
        JSONArray menuMap = JSONArray.parseArray(menus);
        //tree 结构拉直
        LinkedList<JSONObject> list = new LinkedList<>();
        JSONObject resultJson = new JSONObject();
        for (int i = 0; i < menuMap.size(); i++) {
            list.add(menuMap.getJSONObject(i));
        }
        while (!list.isEmpty()) {
            JSONObject item = list.removeFirst();
            resultJson.put(item.getString("path"), item.getString("name"));
            //广度优先算法
            if (item.containsKey("children")) {
                JSONArray children = item.getJSONArray("children");
                for (int i = 0; i < children.size(); i++) {
                    list.addLast(children.getJSONObject(i));
                }
            }
        }
        System.out.println(resultJson);

    }


    public static void compare() throws IOException {
        Path sourcePath = Paths.get("D:\\tangzhichao\\workspace\\electrombileweb\\xblue_v1\\src\\locale\\zh\\i18ncode.js");
        Path targetPath = Paths.get("D:\\tangzhichao\\workspace\\electrombileweb\\xblue_v1\\src\\locale\\en\\i18ncode.js");
        Path outPath = Paths.get("D:", "i18n", "compareI18n.json");

        byte[] buff = Files.readAllBytes(sourcePath);
        String text = new String(buff, StandardCharsets.UTF_8);
        int index = text.indexOf("{");
        JSONObject sourceJson = JSONObject.parseObject(text.substring(index));


        buff = Files.readAllBytes(targetPath);
        text = new String(buff, StandardCharsets.UTF_8);
        index = text.indexOf("{");
        JSONObject targetJson = JSONObject.parseObject(text.substring(index));

        for (Object key : sourceJson.keySet()) {
            JSONObject sjson = sourceJson.getJSONObject(key.toString());
            if (sjson == null) {
                System.out.println(key.toString());
                return;
            }
            JSONObject tjson = targetJson.getJSONObject(key.toString());
            if (tjson == null) {
                tjson = new JSONObject();
                targetJson.put("key", tjson);
            }
            for (String skey : sjson.keySet()) {
                if (tjson.get(skey) == null) {
                    tjson.put(skey, sjson.getString(skey));
                }
            }
        }
        String outString = JSON.toJSONString(targetJson, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);

        Files.write(outPath, ("export default " + outString).getBytes(StandardCharsets.UTF_8));


    }


    public static void getChinese() throws IOException {
        Path outPath = Paths.get("D:", "i18n", "compareI18n.json");

        byte[] buff = Files.readAllBytes(outPath);
        String text = new String(buff, StandardCharsets.UTF_8);
        int index = text.indexOf("{");
        JSONObject sourceJson = JSONObject.parseObject(text.substring(index));
        JSONObject result = new JSONObject();
        int fileIndex = 0;
        for (Object key : sourceJson.keySet()) {
            JSONObject childJson = sourceJson.getJSONObject(key.toString());
            for (Object skey : childJson.keySet()) {
                if (childJson.getString(skey.toString()).matches(".+[\\u4e00-\\u9fa5]+.+")) {
                    result.put(key.toString().concat(".").concat(skey.toString()), childJson.getString(skey.toString()));
                    if (result.size() == 100) {
                        Path outPath1 = Paths.get("D:", "i18n", "cout_compareI18n_" + fileIndex + ".txt");
                        String outString = JSON.toJSONString(result, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                                SerializerFeature.WriteDateUseDateFormat);
                        Files.write(outPath1, ("export default " + outString).getBytes(StandardCharsets.UTF_8));

                        fileIndex++;
                        result.clear();
                    }
                }
            }
        }

    }

    public static void marge() throws IOException {
        Path targetPath = Paths.get("D:\\tangzhichao\\workspace\\electrombileweb\\xblue_v1\\src\\locale\\en\\i18ncode.js");
        byte[] buff = Files.readAllBytes(targetPath);
        String text = new String(buff, StandardCharsets.UTF_8);
        int index = text.indexOf("{");
        JSONObject targetJson = JSONObject.parseObject(text.substring(index));

        Path mergeDir = Paths.get("D:", "i18n", "merge");
        Files.list(mergeDir).forEach(item -> {
            try {
                byte[] buff1 = Files.readAllBytes(item);
                String content = new String(buff1, StandardCharsets.UTF_8);
                int index1 = content.lastIndexOf("export default {");
                int lastIndex = content.lastIndexOf("}");
                content = content.substring(index1 + "export default {".length() - 1, lastIndex + 1);
                //
                System.out.println(item);
                JSONObject jsonObject = JSONObject.parseObject(content);
                for (Object key : jsonObject.keySet()) {
                    String keyStr = key.toString();
                    int keyIndex = keyStr.indexOf(".");
                    String firstKey = keyStr.substring(0, keyIndex);
                    String secondKey = keyStr.substring(keyIndex + 1);
                    JSONObject tmpJson = targetJson.getJSONObject(firstKey);
                    if (tmpJson == null) {
                        tmpJson = new JSONObject();
                    }
                    tmpJson.put(secondKey, jsonObject.getString(key.toString()));
                    targetJson.put(firstKey, tmpJson);
                }
                System.out.println("--");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(item);
            }
        });
        String outString = JSON.toJSONString(targetJson, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);
        Files.write(Paths.get("D:", "i18n", "mergeout.js"), ("export default " + outString).getBytes(StandardCharsets.UTF_8));
    }

    public static void trim() throws IOException {
        Path targetPath = Paths.get("D:\\tangzhichao\\workspace\\electrombileweb\\xblue_v1\\src\\locale\\zh\\i18ncode.js");
        byte[] buff = Files.readAllBytes(targetPath);
        String text = new String(buff, StandardCharsets.UTF_8);
        int index = text.indexOf("{");
        JSONObject targetJson = JSONObject.parseObject(text.substring(index));
        String outString = JSON.toJSONString(targetJson, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);
        Files.write(Paths.get("D:", "i18n", "trim.js"), ("export default " + outString).getBytes(StandardCharsets.UTF_8));
    }


    public static void autoTransfer() throws IOException {
        Path targetPath = Paths.get("D:\\tangzhichao\\workspace\\electrombileweb\\xblue_v1\\src\\locale\\zh\\i18ncode.js");
        byte[] buff = Files.readAllBytes(targetPath);
        String text = new String(buff, StandardCharsets.UTF_8);
        int index = text.indexOf("{");
        JSONObject targetJson = JSONObject.parseObject(text.substring(index));
        //源头
        Map<String, Object> zhListMap = Maps.newHashMap();
        for (Object key : targetJson.keySet()) {
            JSONObject jsonObject = targetJson.getJSONObject(key.toString());
            for (Object skey : jsonObject.keySet()) {
                zhListMap.put(key.toString().concat(".").concat(skey.toString()), jsonObject.get(skey.toString()));
            }
        }

        JSONObject zhClone = JSONObject.parseObject(JSONObject.toJSONString(zhListMap));
        //
        targetPath = Paths.get("D:\\tangzhichao\\workspace\\electrombileweb\\xblue_v1\\src\\locale\\en\\i18ncode.js");
        buff = Files.readAllBytes(targetPath);
        text = new String(buff, StandardCharsets.UTF_8);
        index = text.indexOf("{");
        JSONObject enJson = JSONObject.parseObject(text.substring(index));
        Map<String, Object> enListMap = Maps.newHashMap();
        for (Object key : enJson.keySet()) {
            JSONObject jsonObject = enJson.getJSONObject(key.toString());
            for (Object skey : jsonObject.keySet()) {
                enListMap.put(key.toString().concat(".").concat(skey.toString()), jsonObject.get(skey.toString()));
            }
        }
        //根据源头到目标找
        for (String key : enListMap.keySet()) {
            if (enListMap.get(key) != null) {
                zhListMap.put(key, enListMap.get(key));
            }
        }
        //判断是否有中文
        int count = 0;
        Map<String, Object> autoMap = Maps.newHashMap();
        for (Map.Entry<String, Object> item : zhListMap.entrySet()) {
            if (!item.getValue().toString().matches(".+[\\u4e00-\\u9fa5]+.+")) {
                continue;
            }
            System.out.println(item.getValue());
            if (item.getValue().equals("充电金额")) {
                System.out.println("");
            }
            count++;
            List<String> keys = Lists.newArrayList();
            for (Object enKey : zhClone.keySet()) {
                if (zhClone.get(enKey).equals(item.getValue())) {
                    keys.add(enKey.toString());
                }
            }
            System.out.println(keys);
            for (String enKey : keys) {
                Object word = enListMap.get(enKey);
                System.out.println(enKey + "----" + enListMap.get(enKey));
                if (word == null) {
                    continue;
                }
                String textTmp = word.toString();
                if (!textTmp.matches(".+[\\u4e00-\\u9fa5]+.+")) {
                    autoMap.put(item.getKey(), textTmp);
                    break;
                }
            }
        }
        zhListMap.putAll(autoMap);
        System.out.println(count);
        System.out.println("_--------------------------------------------");
        //结果再转换成
        count = 0;
        JSONObject treeJson = new JSONObject();
        for (Object key : zhListMap.keySet()) {
            String keyStr = key.toString();
            int keyIndex = keyStr.indexOf(".");
            String firstKey = keyStr.substring(0, keyIndex);
            String secondKey = keyStr.substring(keyIndex + 1);
            JSONObject tmpJson = treeJson.getJSONObject(firstKey);
            if (tmpJson == null) {
                tmpJson = new JSONObject();
            }
            String t = zhListMap.get(key.toString()).toString();
            if (t.matches(".+[\\u4e00-\\u9fa5]+.+")) {
                System.out.println(t);
                count++;
            }
            tmpJson.put(secondKey, t);
            treeJson.put(firstKey, tmpJson);
        }
        System.out.println("中文数量:" + count );

        String outString = JSON.toJSONString(treeJson, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);
        Files.write(Paths.get("D:", "i18n", "trim_002.js"), ("export default " + outString).getBytes(StandardCharsets.UTF_8));

    }
}



